package com.help10000.rms.ui.activitys.mine

import android.content.Intent
import android.net.Uri
import android.os.*
import android.provider.Settings
import android.view.View
import com.amir.common.beans.AppVersionInfo
import com.amir.common.beans.AppVersionInfoEntity
import com.amir.common.utils.AppVersionUtils
import com.amir.common.utils.ToastUtil
import com.amir.common.utils.Tools
import com.amir.common.weight.DuplicateClickProxy
import com.help10000.rms.R
import com.help10000.rms.common.ExecutorServiceManager
import com.help10000.rms.mvp.presenter.AppVersionInfoPresenter
import com.help10000.rms.mvp.view.CommonView
import com.help10000.rms.ui.base.BaseActivity
import kotlinx.android.synthetic.main.activity_version_info.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL

/**
 * 版本信息
 */
class AppVersionInfoActivity :
    BaseActivity<AppVersionInfoPresenter, CommonView<AppVersionInfoEntity>>(),
    CommonView<AppVersionInfoEntity>, View.OnClickListener {

    private var fileDownload = false
    private var cancelDown = false
    private var data: AppVersionInfo? = null
    override fun getlayoutId(): Int {
        return R.layout.activity_version_info
    }

    override fun initView() {

    }

    override fun initData(savedInstanceState: Bundle?) {
        currentVersionTv.text = packageManager.getPackageInfo(packageName, 0).versionName
    }

    override fun initListener() {
        super.initListener()
        btn_update.setOnClickListener(DuplicateClickProxy(this))
        mPresenter.checkUpdate()
    }

    override fun finish() {
        super.finish()
        cancelDown = true
    }

    override fun createPresenter(): AppVersionInfoPresenter {
        return AppVersionInfoPresenter(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_update -> {
                btn_update.isEnabled = false
                btn_update.text = "文件下载中"
                btn_update.setBackgroundResource(R.drawable.shape_over_ciry_garybg)

                download_info_tv.visibility = View.VISIBLE
                downloadProgress.visibility = View.VISIBLE
                updateTipTv.visibility = View.INVISIBLE
                if (fileDownload) {
                    installApk()
                } else {
                    if (data != null) {
                        downFile(data!!.UpgradeUrl)
                    }
                }
            }
        }
    }

    override fun onDataSuccess(appVersionInfo: AppVersionInfoEntity) {
        this.data = appVersionInfo.data?.AppVersionInfo
//        var versionCode =
//            getViewContext()?.packageManager?.getPackageInfo(
//                getViewContext()!!.packageName,
//                0
//            )?.versionCode
        var version = AppVersionUtils.getAppVersionName(this.mContext)
//        if (data!!.Id > versionCode!!) {
        if(AppVersionUtils.compareVersion(data!!.Version.toString(), version!!) == true){
            newVersionLayout.visibility = View.VISIBLE
            oldVersionLayout.visibility = View.GONE
        }
    }

    /**
     * 后台在下面一个Apk 下载完成后返回下载好的文件
     *
     * @param httpUrl
     * @return
     */
    var file: File? = null
    private fun downFile(httpUrl: String) {
        ExecutorServiceManager.CACHE_THREAD_EXECUTOR.submit {
            try {
                val url = URL(httpUrl)
                val connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET"
                connection.connectTimeout = 5000
                var fileOutputStream: FileOutputStream? = null
                val inputStream: InputStream?
                if (connection.responseCode == 200) {
                    inputStream = connection.inputStream
                    if (inputStream != null) {
                        val appLength = connection.contentLength
                        file = getFile(httpUrl)
                        fileOutputStream = FileOutputStream(file)
                        val buffer = ByteArray(1024 * 8)
                        var length = 0
                        var total = 0
                        while (!cancelDown && inputStream.read(buffer).also { length = it } != -1) {
                            //写入文件中
                            fileOutputStream.write(buffer, 0, length)
                            //统计进度
                            total += length
                            val result: String = (total * 1.0 / appLength * 100).toString()
                            val message = handler.obtainMessage()
                            message.what = PROGRESS
                            message.obj = result
                            handler.sendMessage(message)
                        }
                        fileOutputStream.close()
                        fileOutputStream.flush()
                    }
                    inputStream.close()
                    if (!cancelDown) {
                        //下载完成,开始安装
                        val message = handler.obtainMessage()
                        message.what = DOWNLOAD_COMPLETE
                        handler.sendMessage(message)
                    }
                } else {
                    //下载完成,开始安装
                    val message = handler.obtainMessage()
                    message.what = DOWNLOAD_FAILD
                    handler.sendMessage(message)
                }

            } catch (e: MalformedURLException) {
                e.printStackTrace()
                handler.sendEmptyMessage(DOWNLOAD_FAILD)
            } catch (e: IOException) {
                e.printStackTrace()
                handler.sendEmptyMessage(DOWNLOAD_FAILD)
            }
        }
    }

    /**
     * 安装APK
     */
    private fun installApk() {
        try {
            btn_update.text = "安装文件中"
            Tools.installApp(this, file)
        } catch (e: Exception) {
            btn_update.isEnabled = true
            btn_update.text = "重新安装"
            btn_update.setBackgroundResource(R.drawable.shape_login_button)
            ToastUtil.show("安装发生异常，请检查安装权限是否授予")

            startInstallPermissionSettingActivity()
        }


    }


    private fun startInstallPermissionSettingActivity() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //注意这个是8.0新API
            val packageURI = Uri.parse("package:$packageName")
            val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
            startActivityForResult(intent, INSTALL_PERMISS_CODE)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 授权完成
        if (resultCode == RESULT_OK && requestCode == INSTALL_PERMISS_CODE) {
            installApk()
        } else {
            ToastUtil.show("授权失败，无法安装应用")
        }
    }

    private val handler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                DOWNLOAD_COMPLETE -> {
                    fileDownload = true
                    ToastUtil.show("下载完成,准备安装！")
                    installApk()
                }
                DOWNLOAD_FAILD -> {
                    ToastUtil.show("文件下载失败,请检查！")
                }
                PROGRESS -> {
                    val result = msg.obj as String
                    download_info_tv.text =
                        "下载进度：${(result.substring(0, 5).toDouble()).toInt()}%"
                    try {
                        downloadProgress?.progress = (result.substring(0, 5).toDouble()).toInt()
                    } catch (e: Exception) {

                    }
                }
            }
        }
    }


    /**
     * 根据传过来url创建文件
     */
    private fun getFile(url: String): File {
        // 使用缓存目录,这个时候不需要申请存储权限
        // 目录不存在，那么创建
        val dir = File(externalCacheDir, "download")
        if (!dir.exists()) {
            dir.mkdir()
        }
        // 创建文件
        return File(dir, getFilePath(url))
    }

    /**
     * 截取出url后面的apk的文件名
     * @param url
     * @return
     */
    private fun getFilePath(url: String): String {
        return url.substring(url.lastIndexOf("/"), url.length)
    }

    companion object {

        private const val PROGRESS = 100 //进度
        private const val DOWNLOAD_COMPLETE = 200 //下载完成
        private const val DOWNLOAD_FAILD = 500 //下载完成
        private const val INSTALL_PERMISS_CODE = 500 //安装权限

    }

}
